# -*- coding: utf-8 -*-

from odoo import models, fields, api
import time
import json
import xmltodict
from datetime import datetime

from odoo import http, exceptions
from odoo.http import request

from .error_code import error_code
from ..tools import defs

from ..weixin.pay import WeixinPay
from ..weixin.helper import md5_constructor as md5

import logging

_logger = logging.getLogger(__name__)

def build_pay_sign(app_id, nonce_str, prepay_id, time_stamp, key, signType='MD5'):
    """
    :param app_id:
    :param nonce_str:
    :param prepay_id:
    :param time_stamp:
    :param key:
    :param signType:
    :return:
    """
    sign = 'appId={app_id}' \
           '&nonceStr={nonce_str}' \
           '&package=prepay_id={prepay_id}' \
           '&signType={signType}' \
           '&timeStamp={time_stamp}' \
           '&key={key}'.format(app_id=app_id, nonce_str=nonce_str, prepay_id=prepay_id,
                               time_stamp=time_stamp, key=key, signType=signType)
    return md5(sign).hexdigest().upper()


class MakePayment(http.Controller):
    @http.route('/pay/wxapp/get-pay-data',
                auth='public', methods=['POST'], csrf=False, type='http')
    def post(self, **kwargs):
        try:
            # user = request.env['res.users'].sudo().search([('sub_domain', '=', sub_domain)])
            # if not user:
            #     return request.make_response(json.dumps({'code': 404, 'msg': error_code[404]}))
            config = request.env["ir.config_parameter"]
            app_id = config.get_param('app_id')
            wechat_pay_id = config.get_param('wechat_pay_id')
            wechat_pay_secret = config.get_param('wechat_pay_secret')
            _logger.info(app_id)
            if not app_id:
                return request.make_response(json.dumps({'code': 404, 'msg': error_code[404]}))

            if not wechat_pay_id or not wechat_pay_secret:
                return request.make_response(json.dumps({'code': 404, 'msg': '未设置wechat_pay_id和wechat_pay_secret'}))

            if 'token' not in kwargs.keys():
                return request.make_response(json.dumps({'code': 300, 'msg': error_code[300].format('token')}))

            token = kwargs.pop('token')
            
            args_key_set = {'order_id', 'money'}

            missing_args_key = args_key_set - set(kwargs.keys())
            # _logger.info(set(kwargs.keys()))
            # _logger.info(missing_args_key)
            if missing_args_key:
                return request.make_response(json.dumps({'code': 600, 'msg': error_code[600]}))
            
                
            access_token = request.env['wechat_mall.access_token'].sudo().search([
                ('token', '=', token)
            ])
            # _logger.info(len(access_token))
            if not access_token:
                return request.make_response(json.dumps({'code': 901, 'msg': error_code[901]}))

            wechat_user = request.env['wechat_mall.user'].sudo().search([
                ('open_id', '=', access_token.open_id)
            ])

            if not wechat_user:
                return request.make_response(json.dumps({'code': 10000, 'msg': error_code[10000]}))
                
            if not int(kwargs['order_id']):
                return request.make_response(json.dumps({'code': 600, 'msg': error_code[600]}))
                # order_record = request.env['cars.rental'].sudo().create({
                #     'customer_id': wechat_user.id,
                # })
            else:
                car_order = request.env['sale.order'].sudo().search([
                ('id', '=', int(kwargs['order_id']))
                ])
                if car_order:
                    order_record = car_order
                else:
                    return request.make_response(json.dumps({'code': 501, 'msg': error_code[501]}))

                    
            # _logger.info(order_record.name)

            payment = request.env['wechat_mall.payment'].sudo().create({
                'order_id':order_record.id,
                'wechat_user_id': wechat_user.id,
                'price': float(kwargs['money'])
            })

            mall_name = config.get_param('mall_name') or '微信小程序商城'
            # base_url = request.env['ir.config_parameter'].get_param('web.base.url')
            base_url = 'https://yuda.einfo-tech.com'
            _logger.info(format(base_url))
	        # _logger.info(format(base_url))
            # _logger.info('dingguaggua')
            wxpay = WeixinPay(appid=app_id, mch_id=wechat_pay_id, partner_key=wechat_pay_secret)
            unified_order = wxpay.unifiedorder(
                body=u'{mall_name}'.format(mall_name=mall_name),
                total_fee=int(float(kwargs['money']) * 100),
                notify_url=u'{base_url}/pay/notify'.format(base_url=base_url),
                openid=u'{}'.format(wechat_user.open_id),
                out_trade_no=u'{}'.format(payment.order_id.name)
            )
            if unified_order['return_code'] == 'SUCCESS' and not unified_order['result_code'] == 'FAIL':
                time_stamp = str(int(time.time()))
                # order_record.state = '2'
                response = request.make_response(
                    headers={
                        "Content-Type": "json"
                    },
                    data=json.dumps({
                        "code": 0,
                        "data": {
                            'timeStamp': str(int(time.time())),
                            'nonceStr': unified_order['nonce_str'],
                            'prepayId': unified_order['prepay_id'],
                            'sign': build_pay_sign(app_id, unified_order['nonce_str'], unified_order['prepay_id'],
                                                   time_stamp, wechat_pay_secret)
                        },
                        "msg": "success"
                    })
                )
            else:
                if unified_order['err_code'] == 'ORDERPAID':
                    order = payment.order_id
                    # order.write({'status': 'pending'})
                    # mail_template = request.env.ref('wechat_mall.wechat_mall_order_paid')
                    # mail_template.sudo().send_mail(order.id, force_send=True, raise_exception=False)
                    # payment.unlink()
                _logger.info("删除了没有啊")
                return request.make_response(
                    json.dumps({'code': -1, 'msg': unified_order.get('err_code_des', unified_order['return_msg'])})
                )
            return response
        except Exception as e:
            _logger.exception(e)
            return request.make_response(json.dumps({'code': -1, 'msg': error_code[-1], 'data': e.message}))


class WechatPaymentNotify(http.Controller):
    @http.route('/pay/notify',
                auth='public', methods=['POST', 'GET'], csrf=False, type='http')
    def post(self, **kwargs):
        _logger.info("notify")
        try:
            xml_data = request.httprequest.stream.read()
            data = xmltodict.parse(xml_data)['xml']
            _logger.info("hjhj")
            if data['return_code'] == 'SUCCESS':
                data.update({'status': defs.PaymentStatus.success})
                order = request.env['sale.order'].sudo().search([
                    ('name', '=', data['out_trade_no'])
                ])
                # order.payment_ids.write(data)
                # order.write({'statement': '1'})
                #------------------------------------------------------
                #------------------------------------------------------
                # _logger.info(int(userid))
                # _logger.info(int(orderid))
                # order = request.env['sale.order'].sudo().search([('id','=',orderid)])
                order = order[0]
                order.state = 'sale'
                _logger.info(order)
                qty = 0
                for i in order.order_line:
                    qty += i.product_uom_qty

                if order.fen_company:
                    fen = request.env['res.partner'].sudo().search([('id','=',order.fen_company.id)])
                    fen = fen[0]
                    fen.stock_no -= qty
                    request.env['fenxiao.stock'].sudo().create({
                        'user':fen.id,
                        'move_no':-qty,
                        'date':datetime.today()
                    })
                # product = request.env['product.template'].sudo().search([('id', '=', int(goodsid))])
                product = order.order_line[0].product_id.product_tmpl_id
                product = product[0]
                product[0].product_no -= qty
                journal = request.env['account.journal'].sudo().search([('name','=',u'客户发票')])
                journal = journal[0]

                Param = request.env()['ir.config_parameter']
                fen_level = Param.get_param('fen_level')
                fen_level = int(fen_level.encode("utf-8"))
                first = float(Param.get_param('first'))
                second = float(Param.get_param('second'))
                third = float(Param.get_param('third'))

                income = Param.get_param('income') or ''
                recipt = Param.get_param('recipt') or ''
                commission = Param.get_param('commission') or ''
                payable_1 = Param.get_param('payable_1') or ''
                payable_2 = Param.get_param('payable_2') or ''
                income = int(income.encode("utf-8"))
                recipt = int(recipt.encode("utf-8"))
                commission = int(commission.encode("utf-8"))
                payable_1 = int(payable_1.encode("utf-8"))
                payable_2 = int(payable_2.encode("utf-8"))

                move = request.env['account.move'].sudo().create({
                    'journal_id': journal.id,
                    'date': datetime.today(),
                    'name': 'INV' + str(datetime.today()),
                    'state': 'posted',
                })

                label='/'
                move.line_ids.sudo().create({
                'move_id': move.id,
                'account_id': recipt,      #微信账户
                'debit': order.amount_total,      #借方金额
                'credit': 0.0,
                'date_maturity': datetime.today(),
                'partner_id': order.partner_id.id,
                'name': label,
                })
                move.line_ids.create({
                'move_id': move.id,
                'account_id': income,   #主营业务收入
                'debit': 0.0,      
                'credit': order.amount_total,
                'date_maturity': datetime.today(),
                'partner_id': order.partner_id.id,
                'name': label,
                })
                if fen_level > 0:
                    money = 0.0
                    if order.third_sale:
                        # money = order.amount_total * third/100
                        money = third
                        c = order.third_sale.commission
                        c += money
                        order.third_sale.commission = c
                        request.env['money.recond'].sudo().create({
                            'user': order.third_sale.id,
                            'sum': '+' + str(money),
                            'data': fields.Date.today()
                        })
                        move.line_ids.create({
                        'move_id': move.id,
                        'account_id': commission,
                        'debit': money,      #借方金额
                        'credit': 0.0,
                        'date_maturity': datetime.today(),
                        'partner_id': order.third_sale.id,
                        'name': label,
                        })
                        move.line_ids.create({
                        'move_id': move.id,
                        'account_id': payable_1,
                        'debit': 0.0,      
                        'credit': money,
                        'date_maturity': datetime.today(),
                        'partner_id': order.third_sale.id,
                        'name': label,
                        })
                    order.third_sale_money = money
                    if fen_level > 1:
                        money_1 = 0.0
                        if order.second_sale:
                            # money_1 = order.amount_total * second/100
                            money_1 = second
                            c = order.second_sale.commission
                            c += money_1
                            order.second_sale.commission = c
                            request.env['money.recond'].sudo().create({
                                'user': order.second_sale.id,
                                'sum': '+' + str(money_1),
                                'data': fields.Date.today()
                            })
                            move.line_ids.sudo().create({
                            'move_id': move.id,
                            'account_id': commission,
                            'debit': money_1,      #借方金额
                            'credit': 0.0,
                            'date_maturity': datetime.today(),
                            'partner_id': order.second_sale.id,
                            'name': label,
                            })
                            move.line_ids.sudo().create({
                            'move_id': move.id,
                            'account_id': payable_1,
                            'debit': 0.0,      
                            'credit': money_1,
                            'date_maturity': datetime.today(),
                            'partner_id': order.second_sale.id,
                            'name': label,
                            })
                        order.second_sale_money = money_1
                        if fen_level > 2:
                            money_2 = 0.0
                            if order.first_sale:
                                # money_2 = order.amount_total * first/100
                                money_2 = first
                                c = order.first_sale.commission
                                c += money_2
                                order.first_sale.commission = c
                                request.env['money.recond'].sudo().create({
                                    'user': order.first_sale.id,
                                    'sum': '+' + str(money_2),
                                    'data': fields.Date.today()
                                })
                                move.line_ids.sudo().create({
                                'move_id': move.id,
                                'account_id': commission,
                                'debit': money_2,      #借方金额
                                'credit': 0.0,
                                'date_maturity': datetime.today(),
                                'partner_id': order.first_sale.id,
                                'name': label,
                                })
                                move.line_ids.sudo().create({
                                'move_id': move.id,
                                'account_id': payable_1,
                                'debit': 0.0,      
                                'credit': money_2,
                                'date_maturity': datetime.today(),
                                'partner_id': order.first_sale.id,
                                'name': label,
                                })
                            order.first_sale_money = money_2

            else:
                data.update({'status': defs.PaymentStatus.fail})
                order = request.env['sale.order'].sudo().search([
                    ('name', '=', data['out_trade_no'])
                ])
                order.payment_ids.write(data)
                order.write({'statement': '4'})

            response = request.make_response(
                headers={
                    "Content-Type": "application/xml"
                },
                data=xmltodict.unparse({
                    'xml': {
                        'return_code': u'SUCCESS',
                        'return_msg': u'SUCCESS'
                    }
                })
            )
            return response

        except Exception as e:
            _logger.info('fu wu qi is error!')
            _logger.exception(e)
            response = request.make_response(
                headers={
                    "Content-Type": "application/xml"
                },
                data=xmltodict.unparse({
                    'xml': {
                        'return_code': u'FAIL',
                        'return_msg': u'服务器内部错误'
                    }
                })
            )
            return response